const {
	Controller
} = require("uni-cloud-router");
const {
	success,
	fail,
	verify_token,
	build_token,
	create_uuid,
	encrypt,
	decrypt,
	isFieldExist,
	whereObj,
	isHttpMethod,
	isAdmin,
	isSuperAdmin,
	isAuthorities,
} = require('mh-utils');
const svgCaptcha = require('svg-captcha');
//静态配置
const createConfig = require('uni-config-center')
const envCfg = createConfig({
	pluginId: 'env'
}).config()

module.exports = class AuthController extends Controller {
	/*
	 * 创建验证码
	 */
	async captcha() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if (isHttpMethod(ctx, 'GET')) {
			var captchaKey = create_uuid();
			var capObj = svgCaptcha.createMathExpr({ //createMathExpr.create 是生成数学加减
				size: 3, // 验证码长度
				ignoreChars: '0oO1ilL', //验证码排除字符
				noise: 0, // 干扰线条数量
				color: true, // 字符是否有颜色
				background: '#fff', // 背景颜色
				width: 104,
				height: 40,
				fontSize: 32,
			});
			try {
				await dbJQL.collection("mh-sys-captcha").add({
					key: captchaKey,
					code: capObj.text
				})
				return success({
					data: {
						key: captchaKey,
						codeImg: capObj.data
					}
				})
			} catch (e) {
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}

	/*
	 * 登录
	 */
	async login() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		const ip = ctx.context.CLIENTIP;
		if (isHttpMethod(ctx, 'POST')) {
			const {
				captchaKey,
				captchaCode,
				username,
				password
			} = ctx.data;
			var nowTime = new Date().getTime();
			try {
				//1、检查验证码
				var res_captcha = await dbJQL.collection("mh-sys-captcha")
					.where(`key=='${captchaKey}'`)
					.get({
						getOne: true
					});
				if (!res_captcha.data || !res_captcha.data.key) return fail({
					message: '验证码已失效，请重新输入'
				});
				if ((nowTime - (res_captcha.data.createTime || 0)) > 5 * 60 * 1000) return fail({
					message: '验证码超时，请重新输入'
				});
				if (res_captcha.data.code.toLocaleLowerCase() != captchaCode.toLocaleLowerCase()) return fail({
					message: '验证码不正确，请重新输入'
				});

				//2、检查账号或手机号、密码
				var where, isPhone;
				if(/^1[3456789][0-9]{9}$/.test(username)){
					isPhone = true;
					where = `phone=='${username}'`
				}else{
					isPhone = false;
					where = `username=='${username}'`
				}
				var res_user = await dbJQL.collection("mh-sys-user")
					.where(where)
					.get({
						getOne: true
					});
				if (!res_user.data || !res_user.data._id) return fail({
					message: (isPhone?'手机号':'用户名')+'不存在，请重新输入'
				});
				if (res_user.data.password != password) return fail({
					message: '密码错误，请重新输入'
				});
				if (res_user.data.deleted == 1) return fail({
					message: '用户已被禁用，请联系管理员'
				});

				//3、用户详细信息，含字段 authorities、roles详细
				var req_user_result = await service.auth.getUserDetails({
					_res_user: res_user
				})
				if (!req_user_result) return fail({
					message: '系统出错[代码50001]，请联系管理员'
				});

				//4、创建 mh-sys-loginsession登录记录
				const login_session_key = create_uuid();
				var authorities = (req_user_result.authorities || []).map(item => {
					return item.authority;
				}).filter(item => {
					if (item) return true;
					return false;
				})
				var roleCodes = (req_user_result.roles || []).map(item => {
					return item.roleCode;
				})
				var _req_user_result = JSON.parse(JSON.stringify(req_user_result))
				delete _req_user_result.password;
				delete _req_user_result.authorities;
				await dbJQL.collection("mh-sys-loginsession")
					.add({
						key: login_session_key,
						loginUserId: res_user.data._id,
						isAdmin: req_user_result.isAdmin, //是否是管理员
						tenantId: res_user.data.tenantId,
						user: JSON.stringify(_req_user_result),
						authorities,
						roleCodes,
						ip: ip,
					})

				// 写入登录日志
				await dbJQL.collection("mh-sys-loginlog")
					.add({
						key: login_session_key,
						loginUserId: res_user.data._id,
						tenantId: res_user.data.tenantId,

						context: JSON.stringify(ctx.context),
						user: JSON.stringify(_req_user_result),
					})


				// 返回结果
				const token = build_token({
					login_session_key
				}, "7 days");

				return success({
					data: {
						access_token: token,
						user: req_user_result
					},
					message: '登录成功'
				})

			} catch (e) {
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}

	/*
	 * 退出登录
	 */
	async logout() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if (isHttpMethod(ctx, 'POST')) {
			try {
				var token = ctx.data.token;
				var vt = await verify_token(token);
				if (vt.code !== 0) return success();
				await dbJQL.collection("mh-sys-loginsession")
					.where(`key=='${vt.payload.login_session_key}'`)
					.remove()
				return success()
			} catch (e) {
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}

	/**
	 * 根据token，获取用户信息
	 */
	async user() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		// 用户详细信息，含字段 authorities、roles详细
		if (isHttpMethod(ctx, 'GET')) {
			var token = '';
			if (envCfg.debug) {
				token =
					'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dpbl9zZXNzaW9uX2tleSI6IjE1MzU1ZmVhLTgxY2YtNGM0Ni1hOTg3LWMwYTkxODBlMDc5YSIsImlhdCI6MTY2NzMwNTUzMiwibmJmIjoxNjY3MzA1NTMyLCJleHAiOjE2Njc5MTAzMzIsInN1YiI6IlRva2VuIEJ1aWxkIn0.PwGOPV-DeYGVC8zEHB2GsSO2rgolYZ6gwlnfFatkkk7a1EKHKK3Is9gYVU-dv0Oxjyt11f2zjlMYRWwn6ewIPqQKxHbKHOHUsdi_bb3vjjenLC2SU7-RrbFU2ZUMkBt4SJXRwpkXP-qREAPQRUZTOc-i_ncw7zcY-SQHwR57dqRKIF-oty7g53M9q0a7sCqq8lMH4o5Yr2yriFIubMI_AcOLbCQTmuKHMTNxbqO0kKVwqWgX4xCyUmtDL6_co77D7hTYO9popw6AITEzL1tnMF5bMETzRYh8DehNpTkXdJphoMGf568OkiQOEsXJVYZLRMlPL7Xtcjhh5Qtc3-qZIg'
			} else {
				token = ctx.event.headers[envCfg.authorizationName.toLocaleLowerCase()];
			}
			if (!token) return fail({
				code: 401,
				message: '无效token'
			})
			var req_user_result = await service.auth.getUserDetails({
				token
			})
			if (!req_user_result) return fail({
				code: 401
			});
			return success({
				data: req_user_result,
			})
		}
	}

	/**
	 * 登录日志
	 */
	async log_inLog() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		try {
			if (isHttpMethod(ctx, 'GET')) {
				if (!isAdmin(ctx) && !isSuperAdmin(ctx)) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
				try {
					var where = "";

					// 查询条件
					var createTimeStart = ctx.data.createTimeStart;
					var createTimeEnd = ctx.data.createTimeEnd;
					var tenantId = ctx.data.tenantId;

					if (isSuperAdmin(ctx)) {
						if (isFieldExist(tenantId)) {
							where = whereObj({
								where,
								query: `tenantId == '${tenantId}'`
							});
						}
					} else {
						where = whereObj({
							where,
							query: `tenantId == '${ctx.auth.tenantId}'`
						});
					}

					if (isFieldExist(createTimeStart)) {
						where = whereObj({
							where,
							query: `createTime >= ${createTimeStart}`
						});
					}
					if (isFieldExist(createTimeEnd)) {
						where = whereObj({
							where,
							query: `createTime <= ${createTimeEnd}`
						});
					}
					where = whereObj({
						where,
						query: `_id != null`
					});
					var sort = ctx.data.sort || 'createTime';
					var order = ctx.data.order || 'desc';
					// 分页
					var page = ctx.data.page || 1;
					var limit = ctx.data.limit || 500;
					var result = await dbJQL.collection("mh-sys-loginlog")
						.where(`${where}`)
						.orderBy(`${sort}`, `${order}`)
						.skip((page * 1 - 1) * limit)
						.limit(limit * 1)
						.get({
							getCount: true
						})
					if (result.data) {
						return success({
							code: 0,
							data: {
								list: result.data,
								count: result.count,
							},
						})
					}
					return fail({
						code: 1,
					})
				} catch (e) {
					uniCloud.logger.error(e)
					return fail({
						code: 500,
						data: e,
						message: e.errMsg
					})
				}
			}
		} catch (e) {
			console.error(e)
		}
	}

	/**
	 * 修改旧密码
	 */
	async updateOldPassword() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'PUT')){
			try{
				var oldPassword = ctx.data.oldPassword;
				var password = ctx.data.password;
				if(!oldPassword || !password) return fail({
					code: 1,
					message: '参数无效'
				})
				var result = await dbJQL.collection("mh-sys-user")
					.where(`_id == '${ctx.auth.loginUserId}' && password == '${oldPassword}'`)
					.update({
						password,
						updateTime: new Date().getTime()
					})
				if(result.updated > 0) {
					return success({
						code: 0,
						message: '操作成功'
					})
				}else{
					return fail({
						code: 1,
						message: '请检查旧密码是否正确，或联系管理员'
					})
				}
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}

};
